package com.acme.team03.history;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

import com.acme.team03.db.DatabaseUtils;
import com.acme.team03.messages.Message;
import com.acme.team03.messages.TextMessage;

public class ChatHistory {
	Connection connection;

	private BlockingQueue<Message> history = new LinkedBlockingQueue<>();

	public ChatHistory() {
		try {
			connection = DatabaseUtils.getConnection("127.0.0.1", 1527);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addMessage(Message msg) {
		history.add(msg);
		persist();
	}

	public void persist() {
		try {
			PreparedStatement stmt = connection
					.prepareStatement("Insert into History (DATESTAMP, TEXT) values(?, ?)");
			while (!history.isEmpty()) {
				Message msg = history.remove();
				stmt.setLong(1, ((java.util.Date) msg
						.getProperty("Date")).getTime());
				stmt.setString(2, ((TextMessage) msg).getText());
				stmt.addBatch();
			}
			stmt.executeBatch();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Queue<Message> getMessages() {
		Queue<Message> msgQueue = new LinkedList<>();
		try {
			PreparedStatement stmt = connection
					.prepareStatement("SELECT * FROM History");
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				java.util.Date date = new java.util.Date(rs.getLong(1));
				String text = rs.getString(2);
				Message msg = new TextMessage(text);
				msg.setProperty("Date", date);
				msgQueue.add(msg);
			}
		} catch (SQLException e) {
			return msgQueue;
		}
		return msgQueue;
	}
}
